<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------
namespace app\xs\service;

use app\xs\model\CmfUserModel;
use app\xs\model\CmfRoleUserModel;
use app\xs\model\XmglZzjgModel;
use app\xs\model\XmglZzjgUserModel;
use Error;
use think\exception;
use think\exception\ErrorException;
use think\facade\Db;

class UserService
{
    //模型关联方法
    protected $relationFilter = ['user'];

    /**
     * 取得用户所属组织机构id数组
     */
    public function getUserZzjgIdArr($user_id = 0){
        if ($user_id == 0) return [];

        $xzu= new XmglZzjgUserModel();
        $idArr = $xzu->where(['user_id'=>$user_id])->column('zzjg_id');
        return $idArr;
    }

    /**
     * 取得用户的角色id数组
     */
    public function getUserRoleIdArr($user_id = 0){
        if ($user_id == 0) return [];

        $cru= new CmfRoleUserModel();
        $idArr = $cru->where(['user_id'=>$user_id])->column('role_id');
        return $idArr;
    }

    /**
     * 取得 机构的 角色的 所有成员
     */
    public function getZzjgRoleUserList($zzjg_id = [], $role_id = [])
    {
        //select id,user_nickname from cmf_user where user_status = 1 and id in (select user_id from cmf_role_user where role_id=8) and id in (select user_id from xmgl_zzjg_user where zzjg_id = 6);
        if (empty($zzjg_id) || empty($role_id)) return [];
        Db::startTrans();
        try {
            //先取得机构的所有用户
            $zum = new XmglZzjgUserModel();
            $zzjgUseridArr = $zum->where('zzjg_id','in', $zzjg_id)->column('user_id');
            //取得此机构的所有角色的用户id
            $rum = new CmfRoleUserModel();
            $roleUseridArr = $rum->where('role_id','in', $role_id)->column('user_id');
            //取得这些用户的数据
            $um = new CmfUserModel();
            $userArr = $um->where([
                ['id', 'in', $zzjgUseridArr],
                ['id', 'in', $roleUseridArr],
                ['user_status', '=', 1]
            ])->order('id desc')->column('id,birthday,user_login,sex,user_nickname');
        } catch (\Exception $e) {
            Db::rollback();
            dump($e);
            //throw new \think\Exception($e->getMessage(), 10006);   //手动抛出异常,$e->getMessage()
            return [];
        }
        return $userArr;
    }
}
